package com.zelma.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.zelma.admin.feign.UserFeignService;
import com.zelma.admin.vo.ResultUserVo;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zelma.common.utils.PageUtils;
import com.zelma.common.utils.Query;

import com.zelma.admin.dao.OrderDao;
import com.zelma.admin.entity.OrderEntity;
import com.zelma.admin.service.OrderService;


@Service("orderService")
@SuppressWarnings("all")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private UserFeignService feignService;

    @Override
    public List <OrderEntity> findOrderInfo (Integer resourceOrderId, String secondParam) throws IOException {

        //同步ES端口
        SearchRequest searchRequest = new SearchRequest("order");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //多条件查询
        BoolQueryBuilder builder = new BoolQueryBuilder();
        //每个条件分别查询
        if (resourceOrderId!=null && resourceOrderId!=0){
            builder.filter(QueryBuilders.termQuery("resourceOrderId",resourceOrderId));
        }
        if (secondParam!=null && !"".equals(secondParam)){
            //feign调用判断是否为手机号或用户名
            ResultUserVo user = feignService.findUserByAll(secondParam);
            //判断user对象是否为空
            if (user!=null){
                //满足条件 执行查询
                Integer userId = user.getUserId();
                builder.filter(QueryBuilders.termQuery("userId",userId));
            }else{
                //不满足条件 secondParam则为订单id
                builder.filter(QueryBuilders.termQuery("orderId",Integer.valueOf(secondParam)));
            }
        }

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        HighlightBuilder.Field highlightTitle =
                new HighlightBuilder.Field("title");
        highlightTitle.highlighterType("unified");
        highlightBuilder.field(highlightTitle);
        searchSourceBuilder.highlighter(highlightBuilder);
        searchSourceBuilder.query(builder);
        searchRequest.source(searchSourceBuilder);

        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        SearchHits hits = searchResponse.getHits();
        TotalHits totalHits = hits.getTotalHits();
// the total number of hits, must be interpreted in the context of totalHits.relation
        long numHits = totalHits.value;
// whether the number of hits is accurate (EQUAL_TO) or a lower bound of the total (GREATER_THAN_OR_EQUAL_TO)
        TotalHits.Relation relation = totalHits.relation;
        float maxScore = hits.getMaxScore();
        ArrayList <OrderEntity> list = new ArrayList <>();
        SearchHit[] searchHits = hits.getHits();
        for (SearchHit hit : searchHits) {
            // do something with the SearchHit
            String index = hit.getIndex();
            String id = hit.getId();
            float score = hit.getScore();
            String sourceAsString = hit.getSourceAsString();
            OrderEntity orderEntity = JSON.parseObject(sourceAsString, new TypeReference <OrderEntity>() {
            });
            orderEntity.setOrderId(Integer.valueOf(id));
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField highlight = highlightFields.get("title");
            if (highlight!=null){
                Text[] fragments = highlight.fragments();
                String fragmentString = fragments[0].string();
            }
            list.add(orderEntity);
        }
        return list;
    }

    @Override
    public void eslist () throws IOException {

        List <OrderEntity> list = baseMapper.selectList(null);

        for (OrderEntity orderEntity : list) {
            IndexRequest request = new IndexRequest("order");
            request.id(String.valueOf(orderEntity.getOrderId()));
            String jsonString = JSONObject.toJSONString(orderEntity);
            request.source(jsonString, XContentType.JSON);
            IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
        }
        System.out.println("=======订单数据同步到ES结束=======");
    }
}